package com.mux.java;

import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;

public class FileVistorsUtil {
	public static void main(String[] args) throws Exception{
		 //handler1();//master remote
		 //handler1();//master  local
		 copyDir();
	}
	
	
	
	/**
	 * 删除文件夹及子目录文件
	 * @throws Exception
	 */
	public static  void  handler1() throws Exception{
	         	Path start = Paths.get("C:\\Users\\Devin.chen\\Desktop\\photo");
			     Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
			         @Override
			         public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
			             throws IOException
			         {
			             Files.delete(file);
			             return FileVisitResult.CONTINUE;
			         }
			         @Override
			         public FileVisitResult postVisitDirectory(Path dir, IOException e)
			             throws IOException
			         {
			             if (e == null) {
			                 Files.delete(dir);
			                 return FileVisitResult.CONTINUE;
			             } else {
			                 // directory iteration failed
			                 throw e;
			             }
			         }
			     });
	}
	
	
	
	/**
	 * 复制文件
	 * @throws Exception
	 */
	public static void copyDir() throws Exception{
				 final Path source = Paths.get("C:\\Users\\Devin.chen\\Desktop\\前端");
			     final Path target = Paths.get("C:\\Users\\Devin.chen\\Desktop\\devin");

			     Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
			         new SimpleFileVisitor<Path>() {
			             @Override
			             public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
			                 throws IOException
			             {
			                 Path targetdir = target.resolve(source.relativize(dir));
			                 try {
			                     Files.copy(dir, targetdir);
			                 } catch (FileAlreadyExistsException e) {
			                      if (!Files.isDirectory(targetdir))
			                          throw e;
			                 }
			                 return FileVisitResult.CONTINUE;
			             }
			             @Override
			             public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
			                 throws IOException
			             {
			                 Files.copy(file, target.resolve(source.relativize(file)));
			                 return FileVisitResult.CONTINUE;
			             }
			         });
			 
		
		
	}
	
}
